package controller.servlets;

import dao.UserDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import modle.User;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "CheckPasswordServlet", value = "/checkPassword")
public class CheckPasswordServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String oldPassword = request.getParameter("oldPassword");
        UserDao LDao = new UserDao();
        // 通过HttpServletRequest对象获取Session对象
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        String type = user.getRoletype();
        String uAcc = user.getUsername();
        int status = LDao.checkAccount(type, uAcc, oldPassword);
        if (status == 2) {
            // 如果旧密码正确，则创建响应并返回成功的消息
            response.setContentType("application/json;charset=utf-8"); // 设置响应类型为JSON格式
            PrintWriter out = response.getWriter(); // 获取响应输出流
            out.print("{\"code\": 0, \"msg\": \"\"}"); // 输出JSON格式的响应数据
            out.flush(); // 刷新缓冲区

        } else {
            // 如果旧密码错误，则创建响应并返回失败的消息
            response.setContentType("application/json;charset=utf-8"); // 设置响应类型为JSON格式
            PrintWriter out = response.getWriter(); // 获取响应输出流
            out.print("{\"code\": -1, \"msg\": \"旧密码错误\"}"); // 输出JSON格式的响应数据
            out.flush(); // 刷新缓冲区
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
